package com.blrs.service.enterprise.seas.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.blrs.VO.ClassVO;
import com.blrs.common.core.domain.AjaxResult;
import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.core.domain.entity.SysUser;
import com.blrs.common.utils.ReflectionUtils;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.EnterpriseInfo;
import com.blrs.domain.EnterprisePersonInfo;
import com.blrs.mapper.*;
import com.blrs.service.enterprise.seas.IHighSeasService;
import com.blrs.system.mapper.SysDeptMapper;
import com.blrs.system.mapper.SysDictDataMapper;
import com.blrs.system.mapper.SysUploadFileMapper;
import com.blrs.system.mapper.SysUserMapper;
import com.blrs.system.service.ISysDeptService;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.domain.HighSeas;
import org.springframework.transaction.annotation.Transactional;

/**
 * 公海管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-08-08
 */
@Service
public class HighSeasServiceImpl implements IHighSeasService
{
    @Autowired
    private HighSeasMapper highSeasMapper;
    @Autowired
    private EnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUploadFileMapper sysUploadFileMapper;
    @Autowired
    private HighSeaRecordMapper highSeaRecordMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private EnterprisePersonInfoMapper enterprisePersonInfoMapper;
    @Autowired
    private ElectricSalesInfoMapper electricSalesInfoMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private HonorManagementMapper honorManagementMapper;
    @Autowired
    private DimIndustryMapper industryMapper;


    /**
     * 查询公海管理
     * 
     * @param enterpriseId 公海管理主键
     * @return 公海管理
     */
    @Override
    public HighSeas selectHighSeasByEnterpriseId(String enterpriseId)
    {
        HighSeas highSeas = highSeasMapper.selectHighSeasByEnterpriseId(enterpriseId);
        if(highSeas!=null){
            highSeas.setUserName(sysUserMapper.selectUserById(highSeas.getCreateId()).getUserName());
            if (Objects.nonNull(highSeas.getAdministrativeArea())){
                highSeas.setAreaName(sysAreaMapper.selectSysAreaByAreaId(highSeas.getAdministrativeArea()).getAreaName());
            }
            if (Objects.nonNull(highSeas.getDevelopManager())){
                highSeas.setDevelopmentName(sysUserMapper.selectUserById(highSeas.getDevelopManager()).getUserName());
            }
            if (Objects.nonNull(highSeas.getBusinessManager())){
                highSeas.setBusinessManagerName(sysUserMapper.selectUserById(highSeas.getBusinessManager()).getUserName());
            }
            String lastRocord=highSeaRecordMapper.selectHighSeaLastRocord(highSeas.getEnterpriseId());
            if (StringUtils.isNotEmpty(lastRocord)){
                highSeas.setLastRecord(lastRocord);
            }
            highSeas.setUrl(sysUploadFileMapper.selectUrlByCode("seas", highSeas.getBusinessLicense()));
        }
        return highSeas;
    }

    /**
     * 查询公海管理列表
     * 
     * @param highSeas 公海管理
     * @return 公海管理
     */
    @Override
    public List<HighSeas> selectHighSeasList(HighSeas highSeas)
    {
//        //根据行政区域快速匹配
//        if (StringUtils.isNotEmpty(highSeas.getAdministrativeArea())) {
//        //查询出该区域下区县区号
//            List<String> areaList = sysAreaMapper.selectAreaListByParentId(highSeas.getAdministrativeArea());
//            highSeas.setAreaList(areaList);
//        }
        List<HighSeas> list = highSeasMapper.selectHighSeasList(highSeas);
//        for (HighSeas seas : list) {
//            seas.setUserName(sysUserMapper.selectUserById(seas.getCreateId()).getNickName());
            //最新进展操作以及最新操作时间
//            if(!StringUtils.isEmpty(seas.getBusinessType())){
//                if(seas.getBusinessType().equals("1")){
//                    if(!seas.getTitle().equals("公海管理")){
//                        if (seas.getTitle().equals("公海记录进展")){
//                            seas.setLastRecord("新增跟进记录");
//                        }else {
//                            seas.setLastRecord("新增"+seas.getTitle());
//                        }
//                    }else{
//                        seas.setFollowTime(seas.getOperateTime());
//                    }
//                }else if(seas.getBusinessType().equals("2")){
//                    if(!seas.getTitle().equals("公海管理")){
//                        if (seas.getTitle().equals("公海记录进展")){
//                            seas.setLastRecord("更新跟进记录");
//                        }else {
//                            seas.setLastRecord("更新"+seas.getTitle());
//                        }
//                    }else{
//                        seas.setLastRecord("更新公海信息");
//                    }
//                }
//            }
//           if (Objects.nonNull(seas.getAdministrativeArea())){
//               seas.setAreaName(sysAreaMapper.selectSysAreaByAreaId(seas.getAdministrativeArea()).getAreaName());
//           }
//          if (Objects.nonNull(seas.getDevelopManager())){
//              seas.setDevelopmentName(sysUserMapper.selectUserById(seas.getDevelopManager()).getUserName());
//          }
//          if (Objects.nonNull(seas.getBusinessManager())){
//              seas.setBusinessManagerName(sysUserMapper.selectUserById(seas.getBusinessManager()).getUserName());
//          }
//            seas.setUrl(sysUploadFileMapper.selectUrlByCode("seas", seas.getBusinessLicense()));
//            seas.setCompanyNo("GH"+seas.getCompanyNo());
       // }
        return list;
    }

    @Override
    public List<HighSeas> selectHighSeasListByIndex(Long orgId) {
      final   HighSeas highSeas = new HighSeas();
      highSeas.setBelongTo(orgId);
        List<HighSeas> list = highSeasMapper.selectHighSeasListByIndex(highSeas);
        for (HighSeas seas : list) {
            //最新进展操作以及最新操作时间
            if(!StringUtils.isEmpty(seas.getBusinessType())){
                if(seas.getBusinessType().equals("1")){
                    if(!seas.getTitle().equals("公海管理")){
                        if (seas.getTitle().equals("公海记录进展")){
                            seas.setLastRecord("新增跟进记录");
                        }else {
                            seas.setLastRecord("新增"+seas.getTitle());
                        }
                    }else{
                        seas.setFollowTime(seas.getOperateTime());
                    }
                }else if(seas.getBusinessType().equals("2")){
                    if(!seas.getTitle().equals("公海管理")){
                        if (seas.getTitle().equals("公海记录进展")){
                            seas.setLastRecord("更新跟进记录");
                        }else {
                            seas.setLastRecord("更新"+seas.getTitle());
                        }
                    }else{
                        seas.setLastRecord("更新公海信息");
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<String> selectSourceByBelongTo(Long orgId) {
        return highSeasMapper.selectSourceByBelongTo(orgId);
    }


    private void updateOrInsertPerson(HighSeas highSeas) throws NoSuchFieldException, IllegalAccessException {
        //判断人员管理中存在该电话
        EnterprisePersonInfo info = new EnterprisePersonInfo();
        info.setPhone(highSeas.getTelephone());
        info.setEnterpriseName(highSeas.getEnterpriseName());
        info.setOrganizationId(SecurityUtils.getOrgId());
        List<EnterprisePersonInfo> personInfoList = enterprisePersonInfoMapper.selectEnterprisePersonInfoListByPhone(info);
        if (StringUtils.isNotEmpty(personInfoList)){
            //修改
            info.setName(highSeas.getContacts());
            info.setEnterpriseId(highSeas.getEnterpriseId());
            info.setEnterpriseName(highSeas.getEnterpriseName());
            info.setOrganizationId(SecurityUtils.getOrgId());
            info.setOrganizationName(SecurityUtils.getOrgName());
            info.setOperateTime(new Timestamp(new Date().getTime()));
            info.setId(personInfoList.get(0).getId());
            enterprisePersonInfoMapper.updateEnterprisePersonInfo(info);
        }else {
            EnterprisePersonInfo enterprisePersonInfo = new EnterprisePersonInfo();
            //新增
            enterprisePersonInfo.setId(UUID.randomUUID().toString());
            enterprisePersonInfo.setPhone(highSeas.getTelephone());
            enterprisePersonInfo.setName(highSeas.getContacts());
            enterprisePersonInfo.setEnterpriseId(highSeas.getEnterpriseId());
            enterprisePersonInfo.setEnterpriseName(highSeas.getEnterpriseName());
            enterprisePersonInfo.setCreateId(SecurityUtils.getUserId());
            enterprisePersonInfo.setOrganizationId(SecurityUtils.getOrgId());
            enterprisePersonInfo.setOrganizationName(SecurityUtils.getOrgName());
            enterprisePersonInfo.setClassificationId("650c44e1-b575-4b62-9d54-1ba9d1e8abb7");
            enterprisePersonInfo.setFilingTime(new Timestamp(new Date().getTime()));
            enterprisePersonInfo.setCreationTime(new Timestamp(new Date().getTime()));
            enterprisePersonInfo.setOperateTime(new Timestamp(new Date().getTime()));
            enterprisePersonInfoMapper.insertEnterprisePersonInfo(enterprisePersonInfo);
        }
    }
    /**
     * 新增公海管理
     *
     * @param highSeas 公海管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertHighSeas(HighSeas highSeas) throws NoSuchFieldException, IllegalAccessException {
        //判断是否在数据库已有相同的客户数据
        //添加归属于(机构id)
        highSeas.setBelongTo(SecurityUtils.getOrgId());
        //判断是否转电销
        if (electricSalesInfoMapper.selectEleByNameAndOrgId(highSeas.getEnterpriseName(),highSeas.getBelongTo())>0){
            return AjaxResult.error("线索客户中已经存在相同企业数据！");
        }
        if (highSeasMapper.selectEnterpriseInfoByName(highSeas.getEnterpriseName(),highSeas.getBelongTo())>0 ){
            return AjaxResult.error("不能添加相同公海信息！");
        }
        //判断客户管理中是否有相同数据，有则不许添加
        if (enterpriseInfoMapper.number(highSeas.getEnterpriseName(),String.valueOf(SecurityUtils.getOrgId()))>0){
            return AjaxResult.error("客户管理中已有相同数据，无法添加");
        }
        ReflectionUtils.setCommonPrivateProperty(highSeas);
        highSeas.setBelongTo(SecurityUtils.getOrgId());
        highSeas.setOrganizationName(SecurityUtils.getOrgName());
        //人员信息
        if(StringUtils.isNotEmpty(highSeas.getContacts())){
            updateOrInsertPerson(highSeas);
        }
        if (highSeasMapper.insertHighSeas(highSeas)>0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    /**
     * 修改公海管理
     *
     * @param highSeas 公海管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateHighSeas(HighSeas highSeas) throws NoSuchFieldException, IllegalAccessException {
        //修改判断重复(公海)
        HighSeas seas = highSeasMapper.selectEnterpriseInfoByNameInfo(highSeas.getEnterpriseName(), SecurityUtils.getOrgId());
        //客户
        EnterpriseInfo enterpriseInfo =enterpriseInfoMapper.selectEnterpriseInfoNameAndOrgId(highSeas.getEnterpriseName(),SecurityUtils.getOrgId());
        if (Objects.nonNull(seas)){
            if (!seas.getEnterpriseId().equals(highSeas.getEnterpriseId())){
                //说明数据库有一条名称一样的记录，并且不是自身
                return AjaxResult.error("不能修改重复数据");
            }
        }
        if (Objects.nonNull(enterpriseInfo)){
            return AjaxResult.error("不能修改成客户管理重复数据");
        }
        //判断线索客户是否存在
        if (electricSalesInfoMapper.selectEleByNameAndOrgId(highSeas.getEnterpriseName(),highSeas.getBelongTo())>0){
            //前面已经判断公海是否有重复，说明这里线索客户是新增的，所以直接查询判断即可
            return AjaxResult.error("线索客户中已经存在相同企业数据！");
        }
//        //查询公海这条记录的编号是否重复
//        final HighSeas highSeasByCompanyNoView=highSeasMapper.selectHighSeasByCompanyNoView(SecurityUtils.getOrgId(),highSeas.getCompanyNo());
//        if (highSeasByCompanyNoView!=null){
//            if (!highSeasByCompanyNoView.getEnterpriseId().equals(highSeas.getEnterpriseId())){
//                return AjaxResult.error("不能修改重复的公司编号");
//            }
//        }
        //人员信息
        if(StringUtils.isNotEmpty(highSeas.getContacts())){
            updateOrInsertPerson(highSeas);
        }
        highSeas.setOperateTime(new Timestamp(new Date().getTime()));
        return AjaxResult.success(highSeasMapper.updateHighSeas(highSeas));
    }

    /**
     * 批量删除公海管理
     * 
     * @param enterpriseIds 需要删除的公海管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteHighSeasByEnterpriseIds(String[] enterpriseIds)
    {
       //删除公海记录对应的进展记录
        highSeaRecordMapper.deleteHighSeaRecordBySedId(enterpriseIds[0]);
        //删除对应的荣誉资质
        honorManagementMapper.deleteHonorManagementByEnterId(enterpriseIds[0]);
        //涉及到退回操作，这里直接使用物理删除
        return highSeasMapper.deleteHighSeasByEnterpriseIds(enterpriseIds);
    }

    /**
     * 删除公海管理信息
     * 
     * @param enterpriseId 公海管理主键
     * @return 结果
     */
    @Override
    public int deleteHighSeasByEnterpriseId(String enterpriseId)
    {
        return highSeasMapper.deleteHighSeasByEnterpriseId(enterpriseId);
    }

    /**
     * 企业信息转公海
     * 1.先根据企业id查询企业信息
     * 2.把企业信息拷贝到公海信息对象中
     * 3.添加到数据库中
     *
     * @param enterpriseIds
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public AjaxResult convertHighSeas(String[] enterpriseIds) {
         //转公海信息来源机构企业，所以需要把dept表中的数据转成公海数据
        if (enterpriseIds.length>0){
            for (String enterpriseId : enterpriseIds) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(enterpriseId));
                //去判断当前用户的对应的公海和客户有没有对应的企业数据（电销不用判断，因为公海有，电销肯定有，电销没有，但公海可能有）
                //判断公海
                if (highSeasMapper.selectHigSeasByOrgName(sysDept.getDeptName(),SecurityUtils.getOrgId())>0){
                    continue;
//                    return AjaxResult.error("公海或者客户或者电销管理中已存在："+sysDept.getDeptName()+"数据");
                }
                if (enterpriseInfoMapper.selectInfoByOrgName(sysDept.getDeptName(),SecurityUtils.getOrgId())>0){
                    continue;
//                    return AjaxResult.error("公海或者客户或者电销管理已存在："+sysDept.getDeptName()+"数据");
                }
                HighSeas highSeas = new HighSeas();
                //因为两张表的字段完全不相同，所以只能手动注入
                 ReflectionUtils.setCommonPrivateProperty(highSeas);
                BeanUtils.copyProperties(sysDept,highSeas);
                highSeas.setBelongTo(SecurityUtils.getOrgId());
                highSeas.setOrganizationName(SecurityUtils.getOrgName());
                highSeas.setCreateId(SecurityUtils.getUserId());
                highSeas.setEnterpriseName(sysDept.getDeptName());
                highSeas.setEnterpriseOrgId(sysDept.getDeptId());
                if(Objects.nonNull(sysDept.getAddress())){
                    highSeas.setEnterpriseAddress(sysDept.getAddress());
                }
                if (sysDept.getCompanyOrigin()!=null){
                    highSeas.setEnterpriseSource(sysDept.getCompanyOrigin());
                }
                if (Objects.nonNull(sysDept.getPhone())){
                    highSeas.setTelephone(sysDept.getPhone());
                }
                if (sysDept.getRegisteredFund()!=null){
                    highSeas.setRegisteredCapital(sysDept.getRegisteredFund());
                }
                if (sysDept.getArea()!=null){
                    highSeas.setAdministrativeArea(sysDept.getArea());
                }
                if (sysDept.getLegalPerson()!=null){
                    highSeas.setLegalRepresentative(sysDept.getLegalPerson());
                }
                if (sysDept.getNature()!=null){
                    highSeas.setEnterpriseNature(sysDept.getNature());
                }
                if (sysDept.getFoundTime()!=null){
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String createTime = sysDept.getFoundTime();
                    Date date = simpleDateFormat.parse(createTime);
                    highSeas.setEstablishmentDate(date);
                }
                HighSeas high = highSeasMapper.selectEnterpriseInfoByNameInfo(sysDept.getDeptName(), SecurityUtils.getOrgId());
                if (Objects.nonNull(high)){
                    //更新
                    updateSeasDeptOrg(high,sysDept);
                    continue;
//                    return AjaxResult.error("不能重复导入相同客户信息,只能进行更新操作");
                }
                highSeas.setEnterpriseId(UUID.randomUUID().toString().replaceAll("-",""));
                highSeasMapper.insertHighSeas(highSeas);
            }
            return AjaxResult.success("转公海成功");
        }else {
            return AjaxResult.error("转公海失败");
        }
    }

    private void updateSeasDeptOrg(HighSeas high, SysDept sysDept) {
       if (sysDept.getCompanyOrigin()!=null){
           high.setEnterpriseSource(sysDept.getCompanyOrigin());
       }
       if (sysDept.getRegisteredFund()!=null){
           high.setRegisteredCapital(sysDept.getRegisteredFund());
       }
       if (sysDept.getLegalPerson()!=null){
           high.setLegalRepresentative(sysDept.getLegalPerson());
       }
       if (sysDept.getNature()!=null){
           high.setEnterpriseNature(sysDept.getNature());
       }
       if (sysDept.getArea()!=null){
           high.setAdministrativeArea(sysDept.getArea());
       }
       if (sysDept.getContacts()!=null){
           high.setContacts(sysDept.getContacts());
       }
       if (sysDept.getPhone()!=null){
           high.setTelephone(sysDept.getPhone());
       }
       if (sysDept.getDeptId()!=null){
           high.setEnterpriseOrgId(sysDept.getDeptId());
       }
       highSeasMapper.updateHighSeas(high);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importExcel(List<HighSeas> list) throws NoSuchFieldException, IllegalAccessException {
        //判断导入的公海信息是否企业名为重复
        List<String> collect = list.stream().map(highSeas -> highSeas.getEnterpriseName()).collect(Collectors.toList());
        //查询数据库中是否有重复的企业名称
        List<HighSeas> oldList = highSeasMapper.selectEnterpriseInfoName(collect.toArray(new String[0]), SecurityUtils.getOrgId());
        // 将 List 转换为 Map，以 enterpriseName 为键，id 为值
        Map<String, String> existingRecords = oldList.stream()
                .collect(Collectors.toMap(
                        HighSeas::getEnterpriseName, // 键：企业名称
                        HighSeas::getEnterpriseId,         // 值：对应的 ID
                        (entity1, entity2) -> entity1        // 值冲突时，以第一个为准
                ));
// 遍历导入的数据
        for (HighSeas highSeas : list) {
            // 校验行政区域
            highSeas.setAdministrativeArea(sysAreaMapper.selectSysAreaByAreaName(highSeas.getAreaName()));
//            if (StringUtils.isEmpty(highSeas.getAdministrativeArea())) {
//                return AjaxResult.error("行政区域不能为空,对应企业为："+highSeas.getEnterpriseName());
//            }

            // 校验企业地址是否为空
            if (Objects.isNull(highSeas.getEnterpriseAddress())) {
                return AjaxResult.error("导入失败, 地址不能为空");
            }
            //所属行业
            highSeas.setIndustry(industryMapper.selectIndustryByIndustryName(highSeas.getIndustry()));

            // 查询开发经理 ID
            SysUser user = new SysUser();
            user.setNickName(highSeas.getDevelopmentName());
            user.setBelongTo(SecurityUtils.getOrgId());
            SysUser sysUser = sysUserMapper.selectUserByNickName(user);
            if (Objects.nonNull(sysUser)) {
                highSeas.setDevelopManager(sysUser.getUserId());
            }
            ReflectionUtils.setCommonPrivateProperty(highSeas);
            highSeas.setBelongTo(SecurityUtils.getOrgId());
            highSeas.setOrganizationName(SecurityUtils.getOrgName());

            // 判断数据库中是否已存在该企业名称
            if (existingRecords.containsKey(highSeas.getEnterpriseName())) {
                // 如果存在，则更新数据
                highSeas.setEnterpriseId(existingRecords.get(highSeas.getEnterpriseName())); // 设置已存在记录的 ID
                highSeasMapper.updateHighSeas(highSeas);
            } else {
                // 如果不存在，则插入新数据
                highSeasMapper.insertHighSeas(highSeas);
                // 处理人员信息（如果电话不为空）
                if (StringUtils.isNotEmpty(highSeas.getTelephone())) {
                    this.updateOrInsertPerson(highSeas);
                }
            }
        }
        return AjaxResult.success("导入成功, 总计处理 " + list.size() + " 条数据");
    }

    @Override
    public void updateClassIds(String[] enterIds, String classId) {
        highSeasMapper.updateClassByIds(enterIds,classId);
    }

    @Override
    public int editBusinessManager(ClassVO classVO) {
       return highSeasMapper.updateBusinessManager(classVO);
    }

    @Override
    public String getMaxEnterpriseNo(Long orgId) {
        return highSeasMapper.getMaxEnterpriseNo(orgId);
    }

}
